/**
 * Created by wtfssd on 2017/9/13.
 */

import { Actions, ActionConst } from 'react-native-router-flux'

import { AsyncStorage } from 'react-native'
import * as request from '../utils/request'
import { Toast } from 'antd-mobile'
import { ERROR_MSG_DURATION } from '../utils/constant'

const STORAGE_KEY = "STORAGE_KEY_STORE";
const mode = {
    namespace: 'store',
    state: {
        loading: false,

        list: [],
        detail: {
            id: 0,
            store_name: "",
            store_introduced: "",
            store_collect: 0,
            store_image: "",
            reated_at: "",
            updated_at: "",

        },

        categoryLoading: false,
        productLoading: false,
        detailLoading: false,
        categoryList: [],
        storeProductList: [],
        selectedCategory: null,
        storeProductListNextPage: null,


        currentTab: 0,
        recommendProduct: [],
    },
    reducers: {
        save(state, {payload}) {
            return {
                ...state, ...payload
            }
        }
    },

    effects: {

        //获取列表
        * fetchList({payload}, {call, put}) {
            yield put({
                type: 'save',
                payload: {
                    loading: true,
                }
            });
            const data = yield call(request.get, request.API.storeList);
            yield put({
                type: 'save',
                payload: {
                    loading: false,
                }
            });

            if (!data) return;

            yield put({
                type: 'save',
                payload: {
                    loading: false,
                    list: data.data.map(item => ({
                        ...item,
                        title: item.store_name,
                        content: item.store_introduced,
                        icon: item.store_image,
                        coupons: [],
                    }))
                }
            })
        },

        //获取列表
        * fetchDetail({payload}, {call, put}) {
            yield put({
                type: 'save',
                payload: {
                    loading: true,
                    detailLoading: true
                }
            });

            const data = yield call(request.post, request.API.storeDetail, payload);
            yield put({
                type: 'save',
                payload: {
                    loading: false,
                    detailLoading: false
                }
            });
            console.log('store_detail', data);
            if (!data) return;
            yield put({
                type: 'save',
                payload: {
                    loading: false,
                    detail: data.data
                }
            });
            yield put({
                type: 'fetchRecommend',
                payload
            })
        },

        //保存信息到本地存储
        * saveUserToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },
        //从本地存储中恢复信息
        * restoreUserFromStorage({payload}, {call, put}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
        },


        //获取店铺自定义菜单
        * fetchCategories({payload}, {call, put}) {
            yield put({
                type: 'save',
                payload: {
                    categoryLoading: true,
                    categoryList: []
                }
            });

            const data = yield call(request.get, request.API.shopCategoryList, {
                ...payload
            });
            yield put({
                type: 'save',
                payload: {
                    categoryLoading: false
                }
            });
            if (!data || typeof data === 'undefined') return;
            if (Array.isArray(data.data)) {
                yield put({
                    type: 'save',
                    payload: {
                        categoryList: data.data
                    }
                });
                if (data.data.length > 0) {
                    yield put({
                        type: 'save',
                        payload: {
                            selectedCategory: data.data[0]
                        }
                    });
                    yield put({
                        type: 'fetchProductList',
                        payload: {
                            ...payload,
                            store_cate_id: data.data[0].id,
                            fresh: true
                        }
                    })
                } else {
                    yield put({
                        type: 'save',
                        payload: {
                            storeProductList: []
                        }
                    })
                }
            }
        },
        * fetchProductList({payload}, {call, put, select}) {
            yield put({
                type: 'save',
                payload: {
                    productLoading: true
                }
            });

            if (payload.fresh) {
                yield put({
                    type: 'save',
                    payload: {
                        storeProductList: []
                    }
                });

                const data = yield call(request.get, request.API.shopProductList, {
                    ...payload
                });
                yield put({
                    type: 'save',
                    payload: {
                        productLoading: false
                    }
                });
                console.log('product_list', data);
                if (!data || typeof data === 'undefined') return;
                yield put({
                    type: 'save',
                    payload: {
                        storeProductListNextPage: data.data.next_page_url
                    }
                });

                if (Array.isArray(data.data.data)) {
                    yield put({
                        type: 'save',
                        payload: {
                            storeProductList: data.data.data
                        }
                    });
                }

            } else {
                const store = yield select(state => state.store);
                if (store.storeProductListNextPage) {
                    const data = yield call(request.get, store.storeProductListNextPage);
                    yield put({
                        type: 'save',
                        payload: {
                            productLoading: false
                        }
                    });
                    console.log('product_list', data);
                    if (!data || typeof data === 'undefined') return;
                    yield put({
                        type: 'save',
                        payload: {
                            storeProductListNextPage: data.data.next_page_url
                        }
                    });
                    if (Array.isArray(data.data.data)) {
                        yield put({
                            type: 'save',
                            payload: {
                                storeProductList: store.storeProductList.concat(data.data.data)
                            }
                        });
                    }

                }
            }
        },

        * selectCategory({payload}, {put}) {
            yield put({
                type: 'save',
                payload: {
                    selectedCategory: payload.selectedCategory
                }
            });

            yield put({
                type: 'fetchProductList',
                payload: {
                    store_id: payload.store_id,
                    store_cate_id: payload.selectedCategory.id,
                    fresh: true
                }
            })
        },


        * clearData({payload}, {put}) {
            yield put({
                type: 'save',
                payload: {
                    categoryLoading: false,
                    productLoading: false,
                    categoryList: [],
                    storeProductList: [],
                    selectedCategory: null,
                    storeProductListNextPage: null,
                }
            })
        },


        //添加收藏
        * addFav({payload}, {call, put, select}) {
            const store = yield select(state => state.store);

            yield put({
                type: 'save',
                payload: {
                    loading: true
                }
            });
            const result = yield call(request.post, request.API.storeFav, payload);
            yield put({
                type: 'save',
                payload: {
                    loading: false
                }
            });
            if (!result || typeof result === 'undefined') return;
            store.detail.store_collect = Number(store.detail.store_collect) === 0 ? 1 : 0;
            yield put({
                type: 'save',
                payload: {
                    ...store
                }
            });
            Toast.success(result.data, ERROR_MSG_DURATION);
        },


        //TODO:暂时无用
        * onTabChange({payload}, {put}) {
            yield put({
                type: 'save',
                payload
            });
            console.log('zhsdfvsdfwr', payload);
        },

        //获取店铺推荐商品
        * fetchRecommend({payload}, {put, seletc, call}) {
            yield put({
                type: 'save',
                payload: {
                    loading: true
                }
            });
            const result = yield call(request.post, request.API.shopRecommend, payload);
            yield put({
                type: 'save',
                payload: {
                    loading: false
                }
            });
            if (!result || typeof result === 'undefined') return;
            if (result.data && typeof result.data !== 'undefined') {
                let recommendProduct = [];
                if (Array.isArray(result.data)) {
                    if (result.data.length > 0) {
                        result.data.map((item) => {
                            if (item) {
                                recommendProduct.push(item);
                            }
                        })
                    }
                } else if (typeof result.data === 'object') {
                    if (result.data) {
                        let keys = Object.keys(result.data);
                        if (keys.length > 0) {
                            if (typeof keys[0] !== 'number' && isNaN(parseInt(keys[0]))) {
                                recommendProduct.push(result.data);
                            } else {
                                keys.map((k) => {
                                    if (result.data[k]) {
                                        recommendProduct.push(result.data[k]);
                                    }
                                })
                            }
                        }
                    }
                }
                yield put({
                    type: 'save',
                    payload: {
                        recommendProduct
                    }
                });
            }
        },
    },

    subscriptions: {
        setup({dispatch}) {}
    },
};

export default mode